package cn.tedu.straw.api.ex;

import cn.tedu.straw.commons.vo.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @RestControllerAdvice 全局异常处理
 * 会将添加了@ExceptionHandler的方法作用到添加了@RequestMapping的方法上
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 统一处理异常，且只需要编写一次，方法必须填写一个异常类型的参数，尽可能的填写较大的异常参数
     *
     * @ExceptionHandler SpringMVC的异常处理注解
     */
    @ExceptionHandler({ServiceException.class, FileUploadException.class})
    public R handlerException(Throwable e) {
        if (e instanceof InviteCodeException) {
            return R.failure(R.State.ERR_INVITE_CODE, e);
        } else if (e instanceof PhoneDuplicateException) {
            return R.failure(R.State.ERR_PHONE_DUPLICATE, e);
        } else if (e instanceof InsertException) {
            return R.failure(R.State.ERR_INSERT_FAIL, e);
        } else if (e instanceof ParameterValidationException) {
            return R.failure(R.State.ERR_PARAMETER_VALIDATION, e);
        } else if (e instanceof ClassDisabledException) {
            return R.failure(R.State.ERR_CLASS_DISABLED, e);
        } else if (e instanceof FileEmptyException) {
            return R.failure(R.State.ERR_UPLOAD_FILE_EMPTY, e);
        } else if (e instanceof FileSizeException) {
            return R.failure(R.State.ERR_UPLOAD_FILE_SIZE, e);
        } else if (e instanceof FileIOException) {
            return R.failure(R.State.ERR_UPLOAD_IO, e);
        } else if (e instanceof FileStateException) {
            return R.failure(R.State.ERR_UPLOAD_FILE_STATE, e);
        } else if (e instanceof FileTypeException) {
            return R.failure(R.State.ERR_UPLOAD_FILE_TYPE, e);
        } else if (e instanceof QuestionNotFoundException) {
            return R.failure(R.State.ERR_QUESTION_NOT_FOUND, e);
        } else if (e instanceof CommentNotFoundException) {
            return R.failure(R.State.ERR_COMMENT_NOT_FOUND, e);
        } else if (e instanceof AccessDeniedException) {
            return R.failure(R.State.ERR_ACCESS_DENIED, e);
        } else if (e instanceof DeleteException) {
            return R.failure(R.State.ERR_DELETE_FAIL, e);
        } else {
            return R.failure(R.State.ERR_UNKNOWN, e);
        }
    }
}
